package com.jason.concurrent.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Author  yslai
 * @Date  2022/9/20 14:11
 * @Description fork join 分支合并代码
 */
class DriverDemo extends RecursiveTask<Integer>{


    private int number = 10;
    private int result;
    private int begin;
    private int end;

    public DriverDemo(int begin,int end){
        this.begin = begin;
        this.end = end;
    }

    /**
     * 执行这个方法进行拆分
     * @return
     */
    @Override
    protected Integer compute() {

        if ((end-begin)<=number)
        {
            for (int i = begin; i <= end; i++) {

                result = result+i;
            }

        }else {
            //拆分右边
            int middle = (begin + end) / 2;
            DriverDemo f1 = new DriverDemo(begin, middle);
            //拆分左边
            DriverDemo f2 = new DriverDemo(middle + 1, end);
            f1.fork();
            f2.fork();
            result = f1.join()+f2.join();
        }
        return result;
    }
}


public class ForkJoinDemo {

    public static void main(String[] args) {
        DriverDemo driverDemo = new DriverDemo(1, 100);
        //放入到线程池进行执行
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(driverDemo);
        Integer integer = null;
        try {
            integer = submit.get();
        } catch (InterruptedException e) {

        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(integer);
    }
}
